package com.glsc.ngateway.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.annotation.PageAccessAnnotation;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Fax;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.FaxRecv;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.service.FaxService;
import com.glsc.ngateway.platform.service.feign.IFeignFaxService;
import com.glsc.ngateway.platform.utils.SpecificationFactory;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/3 10:37
 */
@RestController
@RequestMapping("/fax")
public class FaxController {

    private FaxService faxService;

    @Resource
    private IFeignFaxService feignFaxService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public void setFaxService(FaxService faxService) {
        this.faxService = faxService;
    }

    @PageAccessAnnotation(operMenu = "传真管理_查询", operType = "查看", operDesc = "传真列表")
    @GetMapping("/listpage")
    @ApiOperation(value = "查询传真任务分页")
    public PlatformResponse<Page<Fax>> listpage(
            @ApiParam(value = "发送者电话") @RequestParam(required = false) String senderMobile,
            @ApiParam(value = "接收者电话") @RequestParam(required = false) String receiverPhone,
            @ApiParam(value = "区号") @RequestParam(required = false) String receiverLdc,
            @ApiParam(value = "发送时间") @RequestParam(required = false) Long sendTime,
            @ApiParam(value = "发送日期") @RequestParam(required = false) String sendDate,
            @ApiParam(value = "标题") @RequestParam(required = false) String title,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {


        if (senderMobile != null && senderMobile.isEmpty()) {
            senderMobile = null;
        }
        if (receiverPhone != null && receiverPhone.isEmpty()) {
            receiverPhone = null;
        }
        if (receiverLdc != null && receiverLdc.isEmpty()) {
            receiverLdc = null;
        }

        if (title != null && title.isEmpty()) {
            title = null;
        }
        if (sendTime != null) {
            sendTime = null;
        }

        if (sendDate != null && sendDate.isEmpty()) {
            sendDate = null;
        }

        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = PageConstant.PageSize;
        }

        SpecificationFactory.SpecElement senderMobileE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "senderMobile", senderMobile);
        SpecificationFactory.SpecElement receiverPhoneE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "receiverPhone", receiverPhone);
        SpecificationFactory.SpecElement titleE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.LIKE, "title", title);
        SpecificationFactory.SpecElement receiverLdcE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "receiverLdc", receiverLdc);
        SpecificationFactory.SpecElement sendDateE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "sendDate", sendDate);

        Specification spec = SpecificationFactory.build(SpecificationFactory.OP.AND, senderMobileE, receiverPhoneE, titleE, receiverLdcE, sendDateE);
        Page<Fax> page = faxService.findPage(spec, pageNo, pageSize);

        PlatformResponse<Page<Fax>> ret = PlatformResponse.successData(page);

        System.out.println(ret);
        return ret;
    }


    //    @PageAccessAnnotation(operMenu = "传真管理_查询", operType = "查看", operDesc = "传真列表")
    @GetMapping("/listrecv")
    @ApiOperation(value = "查询接收传真分页")
    public PlatformResponse<Page<FaxRecv>> listrecv(
            @ApiParam(value = "发送者电话") @RequestParam(required = false) String senderPhone,
            @ApiParam(value = "接收者区号") @RequestParam(required = false) String receiverLdc,
            @ApiParam(value = "接收者电话") @RequestParam(required = false) String receiverPhone,
            @ApiParam(value = "接收者姓名") @RequestParam(required = false) String receiverName,
            @ApiParam(value = "接收日期") @RequestParam(required = false) String recvDate,
            @ApiParam(value = "标题") @RequestParam(required = false) String title,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {


        if (senderPhone != null && senderPhone.isEmpty()) {
            senderPhone = null;
        }
        if (receiverPhone != null && receiverPhone.isEmpty()) {
            receiverPhone = null;
        }
        if (receiverLdc != null && receiverLdc.isEmpty()) {
            receiverLdc = null;
        }

        if (title != null && title.isEmpty()) {
            title = null;
        }
        List<Long> value = new ArrayList<>();
        if (recvDate != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                value.add(sdf.parse(recvDate + " 00:00:00").getTime() / 1000);
                value.add(sdf.parse(recvDate + " 23:59:59").getTime() / 1000);
            } catch (ParseException e) {
                logger.error("异常", e);
            }
        }

        if (receiverName != null && receiverName.isEmpty()) {
            receiverName = null;
        }

        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = PageConstant.PageSize;
        }

        SpecificationFactory.SpecElement senderPhoneE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "senderPhone", senderPhone);
        SpecificationFactory.SpecElement receiverPhoneE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "receiverPhone", receiverPhone);
        SpecificationFactory.SpecElement receiverNameE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "receiverName", receiverName);
        SpecificationFactory.SpecElement titleE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.LIKE, "title", title);
        SpecificationFactory.SpecElement receiverLdcE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.EQ, "receiverLdc", receiverLdc);
        SpecificationFactory.SpecElement recvDateE = new SpecificationFactory.SpecElement(SpecificationFactory.Type.BETWEEN, "recvTime", value);

        Specification spec = SpecificationFactory.build(SpecificationFactory.OP.AND, senderPhoneE, receiverNameE, receiverPhoneE, titleE, receiverLdcE, recvDateE);
        Page<FaxRecv> page = faxService.findRecv(spec, pageNo, pageSize);

        PlatformResponse<Page<FaxRecv>> ret = PlatformResponse.successData(page);

        System.out.println(ret);
        return ret;
    }


    @GetMapping("/cancelFax")
    @ApiOperation(value = "撤销传真发送任务")
    public PlatformResponse<?> cancelFax(@ApiParam(value = "传真Id") @RequestParam("id") Long id) {
        logger.info("撤销传真发送任务，任务Id 为：" + id);
        faxService.cancelFax(id);
        return PlatformResponse.success();
    }


    /**
     * @param file
     * @return
     * @throws IOException
     * @description 上传附件
     */
    @RequestMapping(method = RequestMethod.POST, value = "/uploadDoc", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String, String> uploadDoc(@RequestPart(value = "file") MultipartFile[] file) throws IOException {

        logger.info("接收文件，并进行上传");
        Map<String, String> res = new HashMap<>();
        String appendixId = "";
        for (MultipartFile f : file) {
            if (f.getOriginalFilename().endsWith(".pdf")) {
                String fileName = UUID.randomUUID().toString() + ".pdf";
                appendixId = faxService.updateAppendix(fileName, PlatformConstant.UP_LINUX_FILE, f);
                logger.info("接收文件，并进行上传，文件名称为：" + f.getOriginalFilename());
            }
        }
        if (appendixId.equals("")) {
            res.put("code", "-1");
            res.put("msg", "文件上传失败，文件类型错误");
        } else {
            res.put("code", "0");
            res.put("fileId", appendixId);
        }
        return res;
    }


    @GetMapping("/sendFax")
    @ApiOperation(value = "发送传真")
    public String sendFax(
            @ApiParam(value = "发送者") @RequestParam("sender") String sender,
            @ApiParam(value = "接收者") @RequestParam(value = "receiver", required = false, defaultValue = "") String receiver,
            @ApiParam(value = "接收者区号") @RequestParam("ldc") String ldc,
            @ApiParam(value = "接收者电话") @RequestParam("receiverPhone") String receiverPhone,
            @ApiParam(value = "接收者手机") @RequestParam(required = false, value = "receiverMobile", defaultValue = "") String receiverMobile,
            @ApiParam(value = "是否为接收者发送短信") @RequestParam(value = "isReceiverMobile", defaultValue = "0") String isReceiverMobile,
            @ApiParam(value = "发送者电话") @RequestParam(value = "mobile") String mobile,
            @ApiParam(value = "是否为发送者发送短信") @RequestParam(value = "isMessage", defaultValue = "1") String isMessage,
            @ApiParam(value = "标题") @RequestParam("title") String title,
            @ApiParam(value = "附件ID") @RequestParam("fileId") String fileId,
            @ApiParam(value = "是否预约") @RequestParam(value = "isBook", defaultValue = "0") String isBook,
            @ApiParam(value = "发送时间") @RequestParam(required = false, defaultValue = "") String sendTime) {

        String result = feignFaxService.sendFax(sender, receiver, receiverPhone, ldc, mobile, title, fileId, sendTime, receiverMobile, isMessage, isBook, isReceiverMobile);
        return result;
    }


    @RequestMapping(value = "downloadDoc", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<byte[]> downloadDoc(@RequestBody String fileId, HttpServletRequest request) throws IOException {

        JSONObject jsonObject = JSON.parseObject(fileId);
        String targetName = faxService.getFilePathById(jsonObject.getString("fileId"));
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


}
